package bjut.core.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.util.StringUtils;

import java.util.concurrent.*;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/9 20:17
 */
public class ThreadPoolUtil {

    private static final ConcurrentHashMap<String, ExecutorService> THREAD_POOL_MAP = new ConcurrentHashMap<>();

    public static ThreadFactory createThreadFactory(String prefix, Boolean daemon) {
        if (StringUtils.hasLength(prefix)) {
            if (daemon != null) {
                return new ThreadFactoryBuilder()
                        .setNameFormat(prefix + "-%d")
                        .setDaemon(daemon)
                        .build();
            } else {
                return new ThreadFactoryBuilder()
                        .setNameFormat(prefix + "-%d")
                        .build();
            }
        }
        return Executors.defaultThreadFactory();
    }

    public static void shutdownAllThreadPool() {
        THREAD_POOL_MAP.entrySet().parallelStream().forEach(threadPool -> {
            ExecutorService executorService = threadPool.getValue();
            executorService.shutdown();
            try {
                //3秒内任务未完成，强制关闭
                executorService.awaitTermination(3, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

}
